<?php
/**
 * appRain v 0.1.x
 *
 * LICENSE
 *
 * This source file is subject to the MIT license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://www.opensource.org/licenses/mit-license.php
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@apprain.com so we can send you a copy immediately.
 *
 * @copyright  Copyright (c) 2010 appRain, Inc. (http://www.apprain.com)
 * @license    http://www.opensource.org/licenses/mit-license.php MIT license
 *
 * HELP
 * 
 * Official Website 
 * http://www.apprain.com/
 *
 * Download Link
 * http://www.apprain.com/download
 *
 * Documents Link
 * http ://www.apprain.com/documents
 */

/**
 * appRain Core lib class
 * 
 * @author appRain, Inc.
 */
class appRain_Collection extends appRain_Base_Modules_InformationSet
{

	/**
	 * Retrun Site URL
     * Alies of App::Load("Helper/Config")->Load()->baseurl()
     * 
     * @param $sub_part String
     * @param $secure Boolean
     */
    public function baseurl( $sub_part = NULL, $secure = false )
    {
    	return app::load("Helper/Config")->Load()
    									 ->baseurl($sub_part,$secure);
    }

    /**
     * Retrun Skin(Theme) URL  
     * Alies Of App::Load("Helper/Config")->Load()->skinurl()
     * 
     * @param $sub_part String
     * @param $secure Boolean 
     */
    public function skinurl( $sub_part = NULL, $secure = false )
    {
        return App::Load("Helper/Config")->Load()->skinurl($sub_part,$secure);
    }
    
    /**
     * Retrun Base Directory Path 
     * Alies of Ap::Load("Helper/Config")->Load()->basedir();
     * 
     * @param $sub_part String
     */
    public function basedir( $sub_part = NULL )
    {
        return App::Load("Helper/Config")->Load()->basedir($sub_part);
    }

    /**
     * Return Theme Directory Path
     * Alies of App::Load("Helper/Config")->Load()->skindir()
     * 
     * @param $sub_part String
     */
    public function skindir( $sub_part = NULL )
    {
        return App::Load("Helper/Config")->Load()->skindir($sub_part);
    }
    
    /**
     * Fetch File Manage Path
     * 
     * @param $image_name String
     * @return String	
     */
    public function get_img_url( $image_name = '')
    {
        return $this->baseurl("/" . $this->get_config('filemanager_path') .'/' . $image_name);
    }

    /**
     * Fetch File Manage Path
     * 
     * @param $image_name String
     * @return String 
     */
    public function get_img_dir( $image_name = '')
    {
        return $this->basedir("/" . $this->get_config('filemanager_path') .'/' . $image_name);
    }
    
    /**
     * Generate HTML Tag
     * Alies of App::Load("Helper/Html")->get_tag()
     * 
     * @param $tag String
     * @param $options Array
     * @param $innerHtml String
     */
    public function get_tag( $tag = NULL, $options = NULL, $innerHtml = NULL)
    {
       return  App::Load("Helper/Html")->get_tag( $tag, $options, $innerHtml);
    }
    
    
	/**
	 * Get File Manage Path for Supper Admin/User
	 * This function create a directory for user if that does not exsits in specific path
	 * 
	 * @param $path String
	 */
    public function filemanager_path()
    {
    	$userstatusid = $this->getUserStatusId();
		
    	$filemanager_base_dir = App::load("Helper/Config")->get('filemanager_base_dir');
		  	
    	$path = ($userstatusid == 0 ) ? "{$filemanager_base_dir}" : "{$filemanager_base_dir}/{$userstatusid}";
		
		if( !file_exists( $path ))
		{
			if(is_writable("{$filemanager_base_dir}"))
			{
				mkdir($path,0777);	
			}
			else
			{
				die("Not Writeable: $path");
			}
			
		}
		return $path;
    }
    
    /**
     * -Redirect the control
     * - We need to send the subpart of the url here. This public function automatically add base url with give part of url
     * Exampel: redirect('admin/login')
     *
     * @param $url_part String
     * @param $mode String
     * @param $https Boolean
     */
    public function redirect( $url_part = "", $mode = "header", $https = false )
    {
        $url = $this->baseurl($url_part,$https);

        if( $mode == 'javascript')
        {
            echo $this->get_tag("script",array("type" =>"text/javascript"),"window.location = '{$url}';");
        }
        else
        {
            header("location:{$url}");
        }
    }
    
    /**
     *	A sudo function to check admin logged in status 
     */
    public function check_admin_login()
    {
        $admin_info = App::Load("Module/Session")->read('User') ;
        $admin_info['status'] = isset($admin_info['status']) ? $admin_info['status'] : '';
        if( $admin_info['status'] != 'Admin')
        {
            $this->writeRequestURI();
            $this->redirect('/admin/exception_here');
            exit;
        }
    }


    public function hasRequestURI()
    {
       $_redirectToRequestURI =  App::Load("Module/Session")->read("_redirectToRequestURI");
       return ($_redirectToRequestURI == "") ? false : true;
    }

    public function writeRequestURI()
    {
            App::Load("Module/Session")->write("_redirectToRequestURI",App::Load("Helper/Config")->getServerInfo("REQUEST_URI"));
    }

    public function redirectToRequestURI()
    {   
        $redirectURI = App::Load("Helper/Config")->get('http') . App::Load("Helper/Config")->get('host') . App::Load("Module/Session")->read("_redirectToRequestURI"); 
        App::Load("Module/Session")->delete("_redirectToRequestURI");    
        header("location:{$redirectURI}");
        exit;
    }

    public function check_admin_tab_access($tab)
    {
        $user = App::Load('Module/Session')->read('User');
        $user['admin_panel_tabs'] = isset($user['admin_panel_tabs']) ? $user['admin_panel_tabs'] : Array();
        return in_array($tab,$user['admin_panel_tabs']);
    }

    public function setAdminTab($tab="")
    {
        $this->check_admin_login();
        if($this->check_admin_tab_access($tab))
        {
    	    $this->layout = "admin";
            $this->admin_tab = $tab;
        }   
        else
        {
            $this->redirect("/admin/introduction");
        }
    }

   

    /**
     * Check if a user alrady logged in
     * 
     * @param $type String
     */
    public function user_already_loggedin( $type = 'Admin')
    {
        $admin_info = App::Load("Module/Session")->read('User') ;
        $admin_info['status'] = isset($admin_info['status']) ? $admin_info['status'] : '';
        if( $admin_info['status'] == $type)
        {
            $this->redirect('/admin/introduction');
            exit;
        }
    }

    /**
     * Check User Login
     *
     * @return boolean
     */
	public function checkAppUserLogin()
    {
        $loginInfo = App::Load("Module/Session")->read('AppUser') ;
        //pre($loginInfo);
        if(empty($loginInfo))
        {
            $this->redirect('/member/login');
            exit;
        }
        else
        {
            return true;
        }
    }
	
	public function appUserLoggedInId()
	{
		$loginInfo = App::Load("Module/Session")->read('AppUser') ;
		return isset($loginInfo["id"]) ? $loginInfo["id"] : "";
	}
	
    public function check_user_login()
    {
        $admin_info = App::Load("Module/Session")->read('User') ;
        $admin_info['status'] = isset($admin_info['status']) ? $admin_info['status'] : '';

        if( $admin_info['status'] != 'User' && $admin_info['status'] != 'Admin')
        {
            $this->redirect('/');
            exit;
        }
        else
        {
            return true;
        }

    }
    
    /**
     * Is logged in
     *
     * @return boolean
     */
    public function is_user_logged_in()
    {
        $user_info = App::Load("Module/Session")->read('User') ;
        $admin_info['status'] = isset($admin_info['status']) ? $admin_info['status'] : '';
    
        return ($admin_info['status'] == "User") ? true : false;
        
    }

    /**
     * Set Current User status id
     * 0 : Supper Admin
     * -1: Current user
     * ID: A specific User
     * 
     * @param $status_flag Integer
     * @return Self
     */
    public function setUserStatusId($ID = -1)
    {
		App::setUserStatusId($ID);
		
    	return $this;
    }
    
    /**
     * Fetch User Status ID
     * 
     * @param $id Integer
     */
    public function getUserStatusId( $id = NULL)
    {
    	return App::getUserStatusId();
    }
    
    /**
     * Fetch User Setting Set by UserStatusId
     * 
     * @param Array
     */
    public function user_settings()
    {
    	$rte = array();
    	$data = $this->Config->findAllByFkey($this->getUserStatusId());
    	
    	if(!empty($data))
    	{
			foreach( $data['data'] as $key => $val )$rte[$val['soption']] =  $val['svalue'];
    	}
    	
    	return $rte;
    }
    
    /**
     *	This function to return configuration variables
     *  Example 1:  $this->get_config('current_user_id');
     *  Example 2: $this->get_config('imagemanager_path');
     *  
     *  @param $skey String
     *  @param $load String
     */
    public function get_config( $skey = NULL, $load = "site_info" )
    {
		$rtn = NULL;	
		switch( $skey )
		{
			case 'filemanager_path'  :
										return $this->filemanager_path();
										break;
			default:
										return ($load) ? App::Helper("Config")->setUserStatusId($this->getUserStatusId())->load($load)->get($skey) : App::load("Helper/Config")->setUserStatusId($this->getUserStatusId())->get($skey);
										break;
		}
    }

    /** 
     *	This function return current loggedin User Information
     * 
     * @return Mix
     */
    public function current_admin_info($select = NULL)
    {
        $admin_arr = App::Load("Module/Session")->read('User');
        return isset($select) ? $admin_arr[$select] : $admin_arr;
    }

    /**
     * Fetch Admin Navigation Information
     * 
     * @return Array
     */
    public function get_admin_nav()
    {
        return  App::__def()->getInterfaceBuilderDefinition();
    }
    
    /**
     * Admin tab information
     */
    public function get_admin_links( $admin_flag =NULL, $section = NULL)
    {
        global $admintop_arr;
        global $adminleft_arr;		
        $this->set('admintop_arr',$admintop_arr);
        
        if( $section == 'adminleft' )
        {
            return  isset($adminleft_arr[$admin_flag]) ? $adminleft_arr[$admin_flag] : NULL;
        }		
    }


    /**
     * Access level of admin Tab
     * 
     * @param $admin_type String
     * @return Array()
     */
    public function admin_tab_access( $admin_type = NULL )
    {
        $definiation = $this->get_admin_nav();
        $admin_tab_access = array();
        foreach($definiation as $key => $val )
        {
            if( in_array($admin_type,$val['parent']['acl']) ) $admin_tab_access[] =  $key ;
        }
        return $admin_tab_access;
    }
    
       
	public function staticPageNameToMetaInfo($name = NULL)
	{
		$pageInfo = App::PageManager()->getData($name);
		
		if(!empty($pageInfo))
		{
			$this->page_title = $pageInfo['page_title'];
			$this->page_meta_keyowrds = $pageInfo['meta_keywords'];
			$this->page_meta_desc = $pageInfo['meta_description'];	
		}
		
		return $pageInfo;
	}
 }
